/**
 * Created by hejiahui on 2018/5/28.
 */

import CosCloud from 'cos-js-sdk-v5'
// api
//获取cos签名与cos对象
import { uploadCos } from '@/services/axiosDriver'


let  cosInstance = null
import axios from 'axios'
export const initCos = ()=>{
  cosInstance = new CosCloud({
    getAuthorization: function (options, callback) {
        uploadCos('/public/cos/config', {})
        .then(res=>{
        const tempKeys = res.data.data.tempKeys
        callback({
          TmpSecretId: tempKeys.credentials && tempKeys.credentials.tmpSecretId,
          TmpSecretKey: tempKeys.credentials && tempKeys.credentials.tmpSecretKey,
          XCosSecurityToken: tempKeys.credentials && tempKeys.credentials.sessionToken,
          ExpiredTime: tempKeys.expiredTime
        });
      })
    }
  })
}
function imageFilter(files){
  // 是否符合的图片格式和大小
  let isMatch = true
  for (var i = 0, file; file = files[i]; i++) {
    //console.log(file)
    //console.log(file.type)
    if (file.type.indexOf("image") == 0) {
      if (file.size >=  5 * 1024 * 1024) { // 2MB
        this.$toast.show('您上传的第'+ chinese[i] +'张图片大小过大，应小于5M，请重新上传', 3000)
        isMatch = false
      }
    } else {
      this.$toast.show('文件"' + file.name + '"不是图片。请重新上传', 2000)
      isMatch = false
    }
  }
  return isMatch
}
export const uploadImage = async (file, cb , QuillWatch)=>{
  //const isPass = imageFilter(file)
  //if ( isPass == false) {
  //  return false;
  //}
  const imageType = file.name.split('.')[1]
  const name = file.lastModified + parseInt(Math.random()*10000) +'.' + imageType
  if (file.type.indexOf("image") == 0) {
    var result = await imgReady(file)
  }
  var url = await uploadToCloud(result.bigPic, name, QuillWatch)
  console.log('url', url)
  cb && cb(url)
  return url
}

export const uploadSingleBlobImageWithName = async (name, blobUrl)=>{
  var url = await uploadToCloud( blobUrl, name)
  return 'http://' + url
}

export const uploadSingleBlobImage = async (blobObj)=>{
  const imageType = blobObj.type.split('/')[1]
  const name = +Date.now() + parseInt(Math.random()*10000) +'.' + imageType
  var url = await uploadToCloud( blobObj, name)
  return 'http://' + url
}

function uploadToCloud( blob, name ,QuillWatch){
  console.log('name>>>', name)
  var chinese = ['一','二','三','四']
  return new Promise((resolve, reject)=>{
    const Region= 'ap-guangzhou', Bucket = 'ccnf-im-1255573444'
    QuillWatch && QuillWatch.active.uploading()
    // 分片上传文件
    cosInstance.sliceUploadFile({
      Bucket: Bucket,
      Region: Region,
      Key: name,
      Body: blob,
      onHashProgress: function (progressData) {
        console.log('校验中', JSON.stringify(progressData));
      },
      onProgress: function (progressData) {
        console.log('上传中', JSON.stringify(progressData));
        let complete = (progressData.percent * 100 | 0) + '%'
        QuillWatch.active.progress(complete)
      },
    }, function (err, data) {
      console.log(err, data);
      if(err){
        QuillWatch && QuillWatch.active.uploadError()
      }
      if( data && typeof data == 'object' && 'Location' in data ){
        QuillWatch && QuillWatch.active.uploadSuccess()
        resolve(data.Location)
      }

    });
  })
}



function imgReady(obj){
  let self = this
  let reader = new FileReader();
  reader.readAsDataURL(obj);
  return new Promise((resolve, reject) => {
    reader.onload = function (f) {
      let res = this.result;
      let img = new Image();
      img.onload = async () => {
        let compressedData = await compress2(img, obj.type);
        let bigFile = dataURLtoBlob(compressedData.bigPic);
        let smallFile = dataURLtoBlob(compressedData.smallPic);
        //self.previewImages.push(compressedData.smallPic)
        console.log(bigFile, smallFile)
        resolve({ bigPic: bigFile, smallPic: smallFile });
        img = null;
      };
      img.src = res;
    }
  });
}

function compress2 (img, fileType){
  let canvas = document.createElement("canvas");
  let rotateshow, smallshow;
  return new Promise((resolve, reject) => {
    // 判断照片 横竖屏
    EXIF.getData(img, () => {
      EXIF.getAllTags(img);
      let Orientation = EXIF.getTag(img, 'Orientation')
      switch (Orientation) {
        case 6:
          rotateshow = rotateImg(img, 'left', canvas, fileType)
          smallshow = rotateImg(img, 'left', canvas, fileType, 250)
          break;
        case 8:
          rotateshow = rotateImg(img, 'right', canvas, fileType)
          smallshow = rotateImg(img, 'right', canvas, fileType, 250)
          break;
        case 3:
          rotateImg(img, 'bottomRight', canvas, fileType);
          rotateshow = rotateImg(img, 'bottomRight', canvas, fileType)
          smallshow = rotateImg(img, 'bottomRight', canvas, fileType, 250)
          break;
        default:
          rotateshow = rotateImg(img, '', canvas, fileType);//img.src;
          smallshow = rotateImg(img, '', canvas, fileType, 250);
      }
      resolve({ bigPic: rotateshow, smallPic: smallshow })
    })
  })
}
function rotateImg (img, direction, canvas, fileType, compressRate = 600) {
  let min_step = 0;
  let max_step = 3;
  if (img == null) return;
  //img的高度和宽度不能在img元素隐藏后获取，否则会出错
  let height = img.height;
  let width = img.width;
  //分辨比率压缩
  if (width > compressRate  || height > compressRate * 2) {
    let picRate = parseInt(width / compressRate);
    width /= picRate;
    height /= picRate;
  }
  let step = 2;
  if (step == null) {
    step = min_step;
  }
  if (direction == 'right') {
    step++;
    //旋转到原位置，即超过最大值
    step > max_step && (step = min_step);
  }else if(direction == ''){
    step = 0;
  }else if(direction == 'bottomRight'){
    step = 2;
  } else {
    step--;
    step < min_step && (step = max_step);
  }
  let degree = step * 90 * Math.PI / 180;
  let ctx = canvas.getContext('2d');
  switch (step) {
    case 0:
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0, width, height);
      break;
    case 1:
      canvas.width = height;
      canvas.height = width;
      ctx.rotate(degree);
      ctx.drawImage(img, 0, -height, width, height);
      break;
    case 2:
      canvas.width = width;
      canvas.height = height;
      ctx.rotate(degree);
      ctx.drawImage(img, -width, -height, width, height);
      break;
    case 3:
      canvas.width = height;
      canvas.height = width;
      ctx.rotate(degree);
      ctx.drawImage(img, -width, 0, width, height);
      break;
  }
  return canvas.toDataURL(fileType, 0.8);
}
function dataURLtoBlob( dataUrl ){
  var mimeString =  dataUrl.split(',')[0].split(':')[1].split(';')[0]; // mime类型
  var byteString = atob(dataUrl.split(',')[1]); //base64 解码
  var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
  var intArray = new Uint8Array(arrayBuffer); //创建视图
  for ( let i = 0; i < byteString.length; i += 1) {
    intArray[i] = byteString.charCodeAt(i);
  }
  var blob = new Blob([intArray], { type:  mimeString }); //转成blob
  return blob
}
